<template>
  <div>
    <!-- 搜索框 -->
    <search-card>
      <!-- 自定义搜索内容 -->
      <slot name="searchSlot"></slot>
    </search-card>
    <!-- 表格内容 -->
    <el-card shadow="never" class="table-card">
      <el-button size="medium" type="success" v-if="btnConfig.showAddBtn" @click="addRow">
        <el-icon class="icon"><elementCirclePlusFilled/></el-icon> 
        <span class="icon-font">添加</span>
      </el-button>
      <el-button size="medium" type="danger" v-if="btnConfig.showdeleteBtn" @click="deleteRows">
        <el-icon class="icon"><elementDelete/></el-icon> 
        <span class="icon-font">删除</span>
      </el-button>
      <el-button size="medium" type="warning" v-if="btnConfig.showImportBtn" @click="showImportDialog">
        <el-icon class="icon"><elementUploadFilled/></el-icon> 
        <span class="icon-font">导入</span>
      </el-button>
      <!-- 导入界面 -->
      <BtnImport ref="RefBtnImport" v-if="btnConfig.showImportBtn"
        :fileType="btnConfig.fileType"
        :accept="btnConfig.accept"
        :action="btnConfig.action"
        :limits="btnConfig.limits"
        @getData="getData" 
        ></BtnImport>
        <!-- @importInfo="setImportInfo"/> -->
      <!-- 导出按钮 -->
      <BtnExport v-if="btnConfig.showExportBtn"
        :columns = "tableData.columns"
        :data = "tableData.all"
        :title = "exportTitle"
      ></BtnExport>
      
      <!-- 表格内容 -->
      <table-template 
        ref="TableTemplateRef"
        class="main-table"
        :tableData="tableData"
        :tableConfig="tableConfig"
        v-loading="loading"
        @handleDelete="handleRowDelete"
        @handleEdit="handleRowEdit"
      ></table-template>
      <!-- 分页条 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 40, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="tableData.all.length"
        prev-text="上一页"
        next-text="下一页">
      </el-pagination>
    </el-card>
    
    <el-dialog ref="opDialog" 
      v-model="opDialogVisible" 
      :title="opDialogTitle" 
      width="50%"
      @closed="handleCloseDialog">
      <el-form :model="formInfo"
        ref="Dialogform"
        :rules="rules"
        label-width="150px">
        <slot name="dialogSlot"></slot>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="opDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button >
        </span>
      </template>
    </el-dialog>
    
  </div>
</template>

<script>
import { reactive, ref, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import service from '/@/utils/request';
import TableTemplate from '/@/components/table/template/template.vue'
import SearchCard from '/@/components/table/card/search.vue';
import BtnImport from '/@/components/table/button/import.vue';
import BtnExport from '/@/components/table/button/export.vue';
export default {
	name: 'TableTool',
  props:{
    httpInfo: {
      type: Object,
      default: () => {
        return {
          listUrl: '/admin/role/getList'
        }
      }
    },
    pageName:{
      type: String,
      default: () => {
        return ''
      }
    },
    tableConfig:{
      type: Object,
      default: () => {
        return {
          stripe: true,
          maxHeight: null,
          hasSelectionRole: true,
          button:[]
        }
      }
    },
    btnConfig:{
      type: Object,
      default: () => {
        return {
          showAddBtn: true,
          showdeleteBtn: true,
          showImportBtn: true,
          showExportBtn: true,
          fileType: 'notype', // 下载文件模板类型
          acceptType: '.xls,.xlsx', // 文件类型
          action: '/admin/upload/notype', // 文件上传地址
          limits: 0, // 上传数量限制
        }
      }
    },
    dialogInfo:{
      type: Object,
      default: () => {}
    },
    rules:{
      type: Object,
      default: () => {}
    },
    searchInfo: {
      type: Object,
      default: () => {}
    },
  },
  components: {
    SearchCard,
    TableTemplate,
    BtnImport,
    BtnExport,
  },
	setup(props, { emit }) {

    const defaultColumns = [{ // 默认列
      prop: "noop",
      label: "",
      sortable: true,
      showOverflowTooltip: true,
      align: "center"
    }]
    let loading = ref(false) // 表格加载 等待
    let allProps = toRefs(props) // 所有父组件参数
    let httpInfos = allProps.httpInfo  // 获取地址信息
    let pageName = allProps.pageName.value  // 获取页面名信息

    let currentPage = ref(1)
    let pageSize = ref(5)
    let exportTitle = ref(pageName + '数据导出')

    let opDialogVisible = ref(false) // 操作框是否可见
    let opDialogTitle = ref(pageName + '') // 操作框是否可见
    let opDialogMod = ref('') 

    const Dialogform = ref()
    let formInfo = ref()
    let TableTemplateRef = ref()

    let tableData = reactive({ // 表格数据初始化
      columns: [], // 表格标题
      all: [], // 所有的数据 （用于导出数据）
      data: [] // 界面显示的数据
		})

    // ===================== axios ===============
    const getData = async (params) => { // 获取所有数据
      loading.value = true
      let dataInfo = await service.get(httpInfos.value.listUrl, {params: params}) // 获取数据
      if (dataInfo.code === 200) {
        tableData.columns = dataInfo.data.columns != undefined ? dataInfo.data.columns: defaultColumns 
        tableData.all = dataInfo.data.data != undefined ? dataInfo.data.data: []
        console.log('刷新数据！')
        console.log(tableData)
        refreshCurrentData()
      } else {
        tableData.columns = defaultColumns
        tableData.all = []
      }
      loading.value = false
    }

    const deleteData = async (params) => { // 获取所有数据
      loading.value = true
      let dataInfo = await service.post(httpInfos.value.deleteUrl, params) // 获取数据
      if (dataInfo.code === 200) { ElMessage.success(dataInfo.msg); } 
      else { ElMessage.error(dataInfo.msg); }
      getData()
      loading.value = false
    }
    const startLoading = () => { 
      loading.value = true
    }
    const endLoading = () => {
      loading.value = false
    }
    

    const addData = async (params) => { // 添加所有数据
      loading.value = true
      let dataInfo = await service.post(httpInfos.value.saveUrl, params) // 获取数据
      if (dataInfo.code === 200) { ElMessage.success(dataInfo.msg); getData()} 
      else { ElMessage.error(dataInfo.msg); }
      loading.value = false
    }

    const editData = async (params) => { // 添加所有数据
      loading.value = true
      let dataInfo = await service.post(httpInfos.value.updateUrl, params) // 获取数据
      if (dataInfo.code === 200) { ElMessage.success(dataInfo.msg); getData()} 
      else { ElMessage.error(dataInfo.msg); }
      loading.value = false
    }
    // ===================== 分页工具 ===============
    const refreshCurrentData = () =>{ // 界面刷新
      if (tableData.all != undefined) {
        tableData.data = tableData.all.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
      }
    }
    const handleSizeChange = (size) => { // 每页个数改变
      currentPage.value = 1
      pageSize.value = size
      refreshCurrentData()
    }
    const handleCurrentChange = (newPage) => { // 当前页改变
      currentPage.value = newPage
      refreshCurrentData()
    }

    getData() // 获取数据

    const RefBtnImport = ref(); // 导入按钮
    const showImportDialog = () => {
      RefBtnImport.value.showDialog()
    }
    // ===================== 每一行的按钮 ===============
    const handleRowDelete = (index, row) => { // 删除
     ElMessageBox.confirm(
        '确认要删除当前信息?', '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error',
        }
      )
        .then(() => {
          let data = new FormData()
          data.append("ids",row.id+',')
          deleteData(data)
        })
    }

    const handleRowEdit = (index, row) => {
      opDialogVisible.value = true
      opDialogTitle.value = '编辑' + pageName
      opDialogMod.value = 'edit'
      emit('setDialogMod',row)
      formInfo.value= props.dialogInfo
    }
    const handleCloseDialog = () =>{
      Dialogform.value.resetFields()
    }
    // ===================== 表头的按钮 ===============
    const submitForm = () => { // 提交按钮
      Dialogform.value.validate((valid) => {
        if (valid) {
          let data = new FormData()
          for (const [key, val] of Object.entries(props.dialogInfo)) { data.append(key,val) }
          if (opDialogMod.value == 'edit') {
            editData(data)
          }else if(opDialogMod.value == 'add'){
            data.delete('id')
            addData(data)
          }else {
            ElMessage.error('无效操作')
          }
          Dialogform.value.resetFields()
          opDialogVisible.value = false
        } else {
          return false
        }
      })
    }
    const addRow = () => { // 添加
      opDialogVisible.value = true
      opDialogTitle.value = '添加' + pageName
      opDialogMod.value = 'add'
      emit('setDialogMod',{})
      formInfo.value= props.dialogInfo
    }
    const searchBtn = (searchInfo) => { // 添加
      getData({searchInfo:searchInfo})
    }
    const deleteRows = () => {

      ElMessageBox.confirm(
        '确认要删除当前 ' + TableTemplateRef.value.multipleSelection.length + ' 条信息?', '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error',
        }
      )
        .then(() => {
          let ids = ''
          TableTemplateRef.value.multipleSelection.forEach(item => {
            ids = ids + item.id  + ','
          })
          let data = new FormData()
          data.append("ids",ids)
          deleteData(data)
        })
    }

		return {
      opDialogVisible,
      opDialogTitle,
      Dialogform,
      formInfo,
      loading,
      tableData, 
      pageSize,
      currentPage,
      exportTitle,
      RefBtnImport,
      TableTemplateRef,
      getData,
      startLoading,
      endLoading,
      handleRowDelete,
      handleRowEdit,
      handleSizeChange,
      handleCurrentChange,
      addRow,
      deleteRows,
      showImportDialog,
      handleCloseDialog,
      submitForm,
      searchBtn,
    };
	},
};
</script>

<style lang="scss" scoped>
.table-card{
  margin-top: 10px;
}
.pagination{
  margin-top: 10px;
}
.icon{
  margin-left: -5px;
  margin-top: -1px;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
}
.icon-font{
  text-align: center;
  vertical-align: middle;
  display: inline-block;
}
</style>
